import requests
import json
import time

class RedBookCookieGetter:
    def __init__(self):
        self.session = requests.Session()
        self.session.headers.update({
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36",
            "Referer": "https://www.xiaohongshu.com/",
            "Content-Type": "application/json",
        })
    
    def login_by_password(self, username, password):
        """通过账号密码登录获取Cookie"""
        login_url = "https://passport.xiaohongshu.com/login"  # 实际接口需抓包确认
        
        # 准备登录数据（需根据实际接口调整）
        login_data = {
            "username": username,
            "password": password,  # 可能需要加密处理
            "captcha": ""  # 如需验证码，需额外处理
        }
        
        try:
            response = self.session.post(login_url, json=login_data)
            response.raise_for_status()
            
            # 获取并返回Cookie
            cookies = self.session.cookies.get_dict()
            return cookies
        except Exception as e:
            print(f"登录失败: {e}")
            return None
    
    def login_by_qrcode(self):
        """通过二维码登录获取Cookie（更安全）"""
        # 1. 请求生成二维码
        qrcode_url = "https://www.xiaohongshu.com/explore"  # 实际接口需确认
        response = self.session.get(qrcode_url)
        qrcode_data = response.json()
        
        # 2. 打印二维码链接或保存二维码图片
        print(f"请扫码登录：{qrcode_data.get('qrcode_url')}")
        
        # 3. 轮询检查扫码状态
        check_url = "https://passport.xiaohongshu.com/qrcode/check"  # 实际接口需确认
        for _ in range(60):  # 最多等待60秒
            time.sleep(1)
            check_resp = self.session.get(check_url)
            if check_resp.json().get("status") == "success":
                return self.session.cookies.get_dict()
        
        print("扫码超时")
        return None


# 使用示例
if __name__ == "__main__":
    getter = RedBookCookieGetter()
    
    # 方式1：账号密码登录（需确认加密方式）
    # cookies = getter.login_by_password("你的账号", "你的密码")
    
    # 方式2：二维码登录（更安全）
    cookies = getter.login_by_qrcode()
    
    if cookies:
        print("获取Cookie成功：")
        print(json.dumps(cookies, indent=2))
        # 保存Cookie到文件
        with open("redbook_cookies.json", "w") as f:
            json.dump(cookies, f)